package com.wl.dzt.basic.controller;

import com.wl.dzt.basic.ApplicationContext;
import com.wl.dzt.basic.entity.BasicUser;
import com.wl.dzt.basic.user.UserBuilder;
import com.wl.dzt.sys.config.GeetestConfig;
import com.wl.dzt.sys.constant.CommConstant;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.JDao;
import com.wl.dzt.sys.core.dao.select.term.Term;
import com.wl.dzt.sys.response.Result;
import com.wl.dzt.sys.util.GeetestLib;
import com.wl.dzt.sys.util.RequestUtils;
import com.wl.dzt.sys.util.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;


/**
 * @Author wl_code@163.com
 * @Date 2018/6/6/006
 * @Version 1.0
 * @Description 用户控制器
 * 添加极验证方式
 */
@Api(description = "basicUser", tags = "用户基础接口(basic-api)")
@RestController
@RequestMapping("basicUser")
public class BasicUserController {

    @Resource
    private JDao jDao;

    @PostMapping("login")
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uname", value = "账户名", dataType = "String", required = true, defaultValue = "admin", paramType = "form"),
            @ApiImplicitParam(name = "pwd", value = "密码", dataType = "String", required = true, defaultValue = "888888", paramType = "form")
    })
    public Result login(@ApiIgnore BasicUser basicUser, @ApiIgnore HttpServletRequest request, @ApiIgnore String geetest_challenge, @ApiIgnore String geetest_validate, @ApiIgnore String geetest_seccode) {

        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
                GeetestConfig.isnewfailback());

        //从session中获取gt-server状态
        Object gtSdkSessionKey = request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
        if (gtSdkSessionKey != null) {


            int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
            //从session中获取userid
            String userid = (String) request.getSession().getAttribute("userid");

            //自定义参数,可选择添加
            HashMap<String, String> param = new HashMap<>();
            param.put("user_id", userid); //网站用户id
            param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            param.put("ip_address", RequestUtils.getClientIp(request)); //传输用户请求验证时所携带的IP

            int gtResult = 0;
            if (gt_server_status_code == 1) {
                //gt-server正常，向gt-server进行二次验证
                gtResult = gtSdk.enhencedValidateRequest(geetest_challenge, geetest_validate, geetest_seccode, param);
//            System.out.println(gtResult);
            } else {
                // gt-server非正常情况下，进行failback模式验证
//            System.out.println("failback:use your own server captcha validate");
                gtResult = gtSdk.failbackValidateRequest(geetest_challenge, geetest_validate, geetest_seccode);
//            System.out.println(gtResult);
            }

            if (gtResult == 1) {
                // 验证成功
                BasicUser nowUser = jDao.get(BasicUser.class,
                        new Term[]{Term.eq("uname", basicUser.getUname()), Term.eq("pwd", DigestUtils.md5Hex(basicUser.getPwd()))},
                        "areaId.state");
                if (nowUser == null) {
                    return Result.error("用户不存在,请检查用户名或密码");
                } else {
                    // 所属企业域是否可用
                    boolean areaIsOk = nowUser.getAreaId().getId() == null ? true : "1".equals(nowUser.getAreaId().getState()),
                            userIsOk = !"0".equals(nowUser.getState());// 账户是否可用
                    if (areaIsOk && nowUser != null && userIsOk) {
                        request.getSession().setAttribute(CommConstant.BACK_USER_ID, nowUser.getId());
                    }
                    if (!areaIsOk) {
                        return Result.error("您所处的企业域已停封!");
                    } else if (!userIsOk) {
                        return Result.error("您的账户已停封!");
                    } else {
                        return Result.success("登录成功");
                    }
                }

            } else {
                // 验证失败
                return Result.error("验证码验证失败...");
            }
        } else
            return Result.error("极验证失败.....");

    }

    /**
     * 用户极验证配置加载
     *
     * @param request
     * @return
     */
    @ApiIgnore
    @GetMapping("startCaptcha")
    public Result startCaptcha(HttpServletRequest request) {
        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
                GeetestConfig.isnewfailback());
        String resStr;
        String userid = "jshc";

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", RequestUtils.getClientIp(request)); //传输用户请求验证时所携带的IP

        //进行验证预处理
        int gtServerStatus = gtSdk.preProcess(param);
        //将服务器状态设置到session中
        request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
        //将userid设置到session中
        request.getSession().setAttribute("userid", userid);
        resStr = gtSdk.getResponseStr();
        return Result.success("登录成功!").addData(resStr);
    }


    /**
     * 构建用户数据
     * 每次刷新会重新构建 避免权限个人信息等数据不能及时更改
     *
     * @param session
     * @return
     */
    @PostMapping("index")
    @ApiIgnore
    public Result flowerMain(@ApiIgnore HttpSession session) {
        //获取当前用户id
        String userId = (String) session.getAttribute(CommConstant.BACK_USER_ID);
        //获取当前用户对象
        BasicUser basicUser = DB.get(BasicUser.class, userId, "areaId.id", "areaId.organName", "positionId.id", "organId.id",
                "organId.organName", "positionId.stationName");
        //登录用户构建
        UserBuilder<BasicUser> userBuilder = SpringUtil.getBean(ApplicationContext.USER_BUILDER);
        session.setAttribute(CommConstant.BACK_USER_INFO, userBuilder.builder(basicUser));
        return Result.success("构建用户数据成功");
    }

}
